<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId">
    <template v-slot:common>
      <ul :style="item.styles" :class="{'wb-memu': true,'isFixed': isFixed}">
        <li v-for="(item_, index) in lists" :key="item.id + '-' + index" :style="tabStyles[index]" @click.stop="onMenuClick($event, index)">
          <img v-if="item_.url" :src="item_.url" :style="imgStyles">
          <i v-else :class="item_.icon"></i>
          <p v-if="item_.title" class="margin-top-8">{{item_.title}}</p>
        </li>
      </ul>
    </template>
  </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import { EventBus } from '@/store/index'
import { EVENT_HOVER_TYPES } from '@/common/events'
import { utils } from '@/components/utils/utils'
import { wbBase } from '@/components/utils/wbBase'
import { ref } from 'vue'
import { getPxOVwByValue, getPxOrVw } from '@/store/utils'
import { getCompIdByParam } from '@/plugins/utils'
import { isJSON } from '@/plugins/utils'
import { MOBILE_WID_HEI } from '@/common/const-dif'

export default {
  name: 'WbMenu',
  mixins: [utils, wbBase],
  components: {
    InjectTemplate,
  },
  setup () {
    return {
      tabStyles: ref([]),
      tabIndex: ref(0),
      tabStyle: {},
      tabSelectedStyle: {},
      EVENT_HOVER_TYPES: EVENT_HOVER_TYPES,
      anchors: [],
      intervalFunc: null,
      isFixed: ref(false),
      isClick:false,
      interval: null,
      extraNum: 0
    }
  },
  computed: {
     positionCenter(){
       if(this.isH5Edit || this.siteInfo.md.isMobile){
         return {}
       }else{
         return {
          left: '50%',
          transform: 'translateX(-50%)',
        }
       }
     },
    imgStyles(){
      let unit = getPxOrVw()
      let width_ = this.commonAttr.itemWidth + unit
      let height_ = this.commonAttr.itemHeight + unit
      return {
        width: width_,
        height: height_,
      }
    }
  },
  created() {
    this.initTabStyle()

    _.forEach(this.lists , (item) => {
      this.tabStyles.push(this.tabStyle);
      item.commonUrl = item.url;
    })
    this.tabIndex = parseInt(this.commonAttr.tabIndex)

    EventBus.$off("slideTab", this.slideTo)
    EventBus.$on("slideTab", this.slideTo)
  },
  mounted() {
    if(this.isH5Edit){
      return
    }
    let item = this.lists[0]
    if(item && this.commonAttr.isPageFixed){
      if(item.eventType == EVENT_HOVER_TYPES.anchorInPage.type){
        this.$nextTick( () => {
          document.documentElement.addEventListener('scroll', this.onScroll)
        })
      }
    }
    this.intervalFunc = window.setInterval( () => {
      _.forEach(this.lists , (item) => {
        if(item.eventType == EVENT_HOVER_TYPES.anchorInPage.type){
           let relateAnchorCompId = item.value
          let scrollToDom = document.getElementById(relateAnchorCompId)
          if(scrollToDom){
            let scrollTop = scrollToDom.offsetTop
            this.anchors.push({ compId: item.value, scrollTop })
          }
        }
      })
      if(this.anchors.length >= this.lists.length){
        window.clearInterval(this.intervalFunc)
      }
    }, 1000)

    if(this.tabIndex >= 0) {
      this.onMenuClick(null, this.tabIndex)
    }
    if(this.commonAttr.isFixed){
      this.isClick = false
      window.addEventListener('scroll',this.handleScroll)
      this.menuHeight =  this.item.conAttr.height / MOBILE_WID_HEI.adaptiveScale
    }
  },
  methods: {
    handleScroll(){
        let currentScrollTop = document.documentElement.scrollTop
        let menu = document.getElementById(this.item.id)
        if(currentScrollTop  >= menu.offsetTop){
          this.isFixed = true
          if(!this.isClick){
            this.onScroll(this.menuHeight)
          }
        }else{
          this.isFixed = false
        }
    },
    onScroll (extraNum = 0) {
      let scrolled = document.documentElement.scrollTop || document.body.scrollTop
      let len = this.anchors.length - 1
      for(let i = 0; i < len; i++){
        if(scrolled >= this.anchors[len].scrollTop - extraNum){
          this.tabIndex = len
          this.initTabStyle()
          this.refreshTab()
          break
        }else if(scrolled >= this.anchors[i].scrollTop  - extraNum && scrolled  < this.anchors[i+1].scrollTop - extraNum){
          this.tabIndex = i
          this.initTabStyle()
          this.refreshTab()
          break
        }
      }
    },
    slideTo({slideIndex}) {
      this.tabIndex = parseInt(slideIndex)
      this.initTabStyle()
      this.refreshTab()
    },
    onMenuClick(e, itemIndex){
      this.isClick = true
      this.tabIndex = itemIndex
      this.initTabStyle()
      this.refreshTab()
      this.commonAttr.itemIndex = itemIndex
      //组件的固有点击事件
      // if(this.item.cid == COMPONENT_TYPES.wb_menu){
        //1 网页链接、2 页面跳转、3 弹层页面
        let item_ = this.item.lists[itemIndex]
        // let jumpUrl = item_.value
        if(item_.eventType == EVENT_HOVER_TYPES.link.type){
          if(item_.value.indexOf("http") != -1 || item_.value.indexOf("sinaweibo") != -1){
            this.openLinkBySelfUrl(item_.value);
          }
        }else if(item_.eventType == EVENT_HOVER_TYPES.anchor.type){
          let pageId = item_.value
          this.showPage(pageId)
        }else if(item_.eventType == EVENT_HOVER_TYPES.layer.type){
          let popId = item_.value//.replace(/[^0-9]/ig,"")
          this.showPop(popId)
        }else if(item_.eventType == EVENT_HOVER_TYPES.anchorInPage.type){
          let relateAnchorCompId = item_.value
          let scrollToDom = document.getElementById(relateAnchorCompId)
          if(scrollToDom){
            if(this.commonAttr.isFixed){
              // 站点2456 吸顶菜单
              this.scrollToTop(scrollToDom.offsetTop, this.menuHeight)
              this.interval = window.setInterval(()=>{
                if(parseInt(scrollToDom.offsetTop - this.menuHeight) == parseInt(document.documentElement.scrollTop)){
                  window.clearInterval(this.interval)
                  this.isClick = false
                }
              },100)
            }else{
              this.scrollToTop(scrollToDom.offsetTop)
            }
          }
        }else if(item_.eventType == 'compVisibleInComps'){
          this.$store.commit('resetVisibleComponents_')
          let relateAnchorCompId = getCompIdByParam(item_.value) || item_.value;
          let commonAttr = { isVisible: true }
          this.$store.commit('updateComponentVisible', { id: relateAnchorCompId, commonAttr })
          //触发懒加载 加载 图片
          document.documentElement.scrollTop = document.documentElement.scrollTop + 1
          document.documentElement.scrollTop = document.documentElement.scrollTop - 1
          let relateAnchorCompData = this.componentMap[relateAnchorCompId];
          let heightEffectParams = this.item.commonAttr.heightEffectParams;//{distanceBottom:500,compId:""} 1789
          let heightEffectObj = null;
          let pageHeight = 0;
          if(relateAnchorCompData) {
            if(heightEffectParams && isJSON(heightEffectParams)){
              heightEffectObj = JSON.parse(heightEffectParams);
              pageHeight = relateAnchorCompData.conAttr.top + relateAnchorCompData.conAttr.height + parseInt(heightEffectObj.distanceBottom);
              //更新组件位置 2032 510国货大赏{"distanceBottom":500,"compId":"19133ff3-b964-4cf8-a9f0-8deb6649947d","top":40}
              this.$nextTick(() => {
                let compId = heightEffectObj.compId;
                let relateAnchorCompData = this.componentMap[relateAnchorCompId];
                let top = heightEffectObj.top ? heightEffectObj.top : 20;
                this.$store.commit("updateComponentAttr", { id: compId, conStyles: { top: getPxOVwByValue(relateAnchorCompData.conAttr.top + relateAnchorCompData.conAttr.height + top) } });
              })
            }else{
              pageHeight = relateAnchorCompData.conAttr.top + relateAnchorCompData.conAttr.height;
            }
            // 更新页面的高度
            let currentPage = this.pages[this.pageId - 1];
            this.$store.commit('updatePageAttr', { id: currentPage.id, styles: { height: getPxOVwByValue(pageHeight) } });
          }
        }
        let jumpUrl = "wb-menu-" + itemIndex
        let comType = "click"
        let wModule = "jump"
        this.onPostStatics(e, { comType, wModule,  jumpUrl })
      // }
    },
    scrollToTop(scrollTop,extraNum = 60){
      window.scrollTo({top: scrollTop - extraNum, behavior: 'smooth'});
    },
    refreshTab(){
      if(this.isH5Edit){
        return
      }
      this.tabStyles = []
       _.forEach(this.lists , (item) => {
        this.tabStyles.push(this.tabStyle);
        item.url = item.commonUrl;
      })
      this.tabStyles[this.tabIndex] = this.tabSelectedStyle;
      if(this.lists[this.tabIndex].selectedBgUrl){
        this.lists[this.tabIndex].url = this.lists[this.tabIndex].selectedBgUrl;
      }
      //强制tab按钮渲染，不可删除这行代码，虽然看着没啥用
      // this.tabStyles = _.cloneDeep(this.tabStyles)
    },
    initTabStyle(){
      let style = {}
      let unit = getPxOrVw()
      style.borderTopLeftRadius = this.commonAttr.itemBorderRadius + unit
      style.borderTopRightRadius = this.commonAttr.itemBorderRadius + unit

      style.borderBottomLeftRadius = 0
      style.borderBottomRightRadius = 0
      style.padding = this.commonAttr.paddingTB + unit + ' ' + this.commonAttr.paddingLR + unit;
      style.margin = this.commonAttr.marginTB + unit + ' ' + 0 + unit;

      _.merge(this.tabSelectedStyle, style)
      this.tabSelectedStyle.backgroundColor = this.commonAttr.itemSeletedBGColor
      this.tabSelectedStyle.color = this.commonAttr.selectedColor
      this.tabSelectedStyle.fontSize = this.commonAttr.fontSize + unit

      _.merge(this.tabStyle, style)
      this.tabStyle.backgroundColor = this.commonAttr.itemBGColor
      this.tabStyle.color = this.item.styles.color
      this.tabStyle.fontSize = this.commonAttr.fontSize + unit
    }
  },
  beforeUnmount(){
    EventBus.$off("slideTab", this.slideTo)
    if(this.commonAttr.isFixed){
      window.removeEventListener('scroll',this.handleScroll)
      if(this.interval) window.setInterval(this.interval)
    }
  }
};
</script>

<style lang="scss">
.wb-memu{
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
  height: inherit;
  width: inherit;

  display: flex;
  flex-direction: row;
  justify-content: space-around;
  flex-wrap: wrap;

  li {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    font-size: inherit;
    color: inherit;
    flex-grow: 1;

    img {
      object-fit: contain;
    }
    p{
      font-size: inherit;
    }
    i{
      font-size: inherit;
    }
    a{
      visibility: hidden;
    }
  }
}
.isFixed{
  position: fixed;
  top: 0;
  z-index: 99999;
}

</style>
